package com.talking.controller.retrieve;

import com.talking.pojo.Message;
import com.talking.pojo.User;
import com.talking.service.MailService;
import com.talking.service.SocketService;
import com.talking.service.UserService;
import com.talking.view.componentpojo.LoginFrameObj;

import javax.swing.*;
import java.util.regex.Pattern;

public class RetrieveController {
    private UserService userService;
    private MailService mailService;

    public RetrieveController(String mail,String code,String pwd,String rePWD){
        userService = new UserService();
        mailService = new MailService();

        boolean mailFlag = Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", mail);
        boolean codeFlag = Pattern.matches("[0-9]{4}",code);
        boolean pwdFlag = Pattern.matches("[A-Za-z0-9]{8,20}",pwd);
        boolean rePWDFlag = pwd.trim().equals(rePWD.trim());

        if (mailFlag&&codeFlag&&pwdFlag&&rePWDFlag) {

            if (this.verifyCode(mail, code))
                this.retrieve(mail, pwd);
            else
                JOptionPane.showMessageDialog(null, "验证码错误", "错误提示：", JOptionPane.WARNING_MESSAGE);
        }else {
            if (!mailFlag)
                JOptionPane.showMessageDialog(null, "邮箱输入非法", "错误提示：", JOptionPane.WARNING_MESSAGE);
            else if (!codeFlag)
                JOptionPane.showMessageDialog(null, "验证码输入非法", "错误提示：", JOptionPane.WARNING_MESSAGE);
            else if (!pwdFlag)
                JOptionPane.showMessageDialog(null, "密码仅支持字母与数字，长度为：8~20", "错误提示：", JOptionPane.WARNING_MESSAGE);
            else if (!rePWDFlag)
                JOptionPane.showMessageDialog(null, "密码与重复密码不一致", "错误提示：", JOptionPane.WARNING_MESSAGE);
        }

    }

    //验证验证码
    private boolean verifyCode(String user_mail,String mail_code){
        User user = new User();
        user.setUser_mail(user_mail);
        user.setUser_pwd(mail_code);
        boolean flag = mailService.verifyMailCode(user);

        return flag;
    }

    //找回密码
    public void retrieve(String mail,String pwd){
        Message inMSG = new Message();
        User user = new User();
        user.setUser_mail(mail);
        user.setUser_pwd(pwd);

        userService.updateUserMSG(user,null);
        try {
           inMSG = (Message) SocketService.getClientInput().readObject();

           if (inMSG.isResponseType()) {
               JOptionPane.showMessageDialog(null, "找回密码成功", "密码重置", JOptionPane.WARNING_MESSAGE);
               LoginFrameObj.getCardLayout().show(LoginFrameObj.getContainer(),"0");
           }
           else JOptionPane.showMessageDialog(null, "找回密码失败！", "密码重置", JOptionPane.WARNING_MESSAGE);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
